package com.zjxf.utils;

import com.zjxf.base.common.OperationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 实体类转换
 *
 * @author ZhangWei
 * @date 2021/4/6/006 11:11
 */
@Slf4j
public class Conversion {


    /**
     * vo转po
     *
     * @param vo 原对象
     * @param po 返回的对象
     * @return Object
     */
    public static <T> T voTurnPo(Object vo, T po) {
        BeanUtils.copyProperties(vo, po);
        return po;
    }

    /**
     * po转ro
     *
     * @param po 原对象
     * @param ro 返回的对象
     * @return Object
     */
    public static <T> T poTurnRo(Object po, T ro) {
        BeanUtils.copyProperties(po, ro);
        return ro;
    }

    /**
     * poList 转 roList
     *
     * @param sourceList 原对象
     * @param t          返回的对象
     * @param <T>        返回对象的枚举
     * @param <E>        原对象的枚举
     * @return List<T>
     * @throws OperationException 自定义异常
     */
    public static <T, E> List<T> poListTurnRoList(List<E> sourceList, T t) throws OperationException {
        List<T> voList = new ArrayList<>();
        for (E po : sourceList) {
            Class<?> aClass = t.getClass();
            Object ro = tryCatch(aClass);
            BeanUtils.copyProperties(po, ro);
            voList.add((T) ro);
        }
        return voList;
    }

    /**
     * 异常捕获(反射获取对象)
     *
     * @param aClass 被实例化的对象
     * @return Object
     * @throws OperationException 自定义异常
     */
    private static Object tryCatch(Class<?> aClass) throws OperationException {
        try {
            return aClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            log.error("无法访问对象中的属性");
            e.printStackTrace();
            throw new OperationException("无法访问对象中的属性");
        } catch (IllegalAccessException e) {
            log.error("对象是接口或者抽象类");
            e.printStackTrace();
            throw new OperationException("poList转roList失败");
        }
    }
}
